from operator import itemgetter
import requests
from plotly import offline
url = "https://hacker-news.firebaseio.com/v0/topstories.json"
r = requests.get(url)
print(f"status code: {r.status_code}")
# 处理有关每篇文章的信息
submission_ids = r.json()
submission_dicts, repo_links, owners, comments = [], [], [], []
for submission_id in submission_ids[:30]:
	# 对于每篇文章，都执行一个API调用
	url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
	r = requests.get(url)
	response_dict = r.json()
	# 对于每篇文章，都创建一个字典
	submission_dict = {
	    "title": response_dict["title"],
	    "hn_link":
			f"http://news.ycombinator.com/item?id={submission_id}",
		"comments": response_dict["descendants"],
		"owner": response_dict["by"]
		}
	submission_dicts.append(submission_dict)
# 提取标签
for submission_dict in submission_dicts:
	repo_name = submission_dict["title"]
	repo_url = submission_dict["hn_link"]
	repo_link = f"<a href='{repo_url}'>{repo_name}</a>"
	repo_links.append(repo_link)
	comments.append(submission_dict["comments"])
	owners.append(submission_dict["owner"])
# submission_dicts = sorted(submission_dicts, key=itemgetter("comments"),reverse=True)
# 可视化
data = [{
    "type": "bar",
    "x": repo_links,
    "y": comments,
    "hovertext": owners,
    "marker": {
    "color": "rgb(60, 100, 150)",
    "line": {"width": 1.5, "color": "rgb(25, 25, 25)"}
    },
    "opacity": 0.6
}]
my_layout = {
    "title": "按照评论数看受欢迎的文章",
	"font": {"size": 28},
	"xaxis": {
	    "title": "文章名",
	    "tickfont": {"size": 14},
	},
	"yaxis": {
	    "title": "评论数",
	    "tickfont": {"size": 14},
	},
}
fig = {"data": data, "layout": my_layout}
offline.plot(fig, filename="hn_submissions_visual.html")
		
		
